#include "tokenlist.h"


/* create a new list */
struct tokenlist * newlist()
{
	struct tokenlist *temp = (struct tokenlist *)malloc(sizeof(struct tokenlist));
	temp->head = NULL;
	temp->tail = NULL;
	temp->current = NULL;
	temp->tokenum = 0;
	temp->errcheck =0;

	return temp;
}

/* create a new token in list */

/* int token */
struct token * new_int_token(int linev, union value intv)
{
	struct token *tempt;
	tempt = (struct token *) malloc (sizeof(struct token)); /*allocate memory */

	tempt->v = intv;
	tempt->type = INTEGER;
	tempt->linenum = linev;

	return tempt;
}

/* float token */
struct token * new_float_token(int linev, union value fv)
{
	struct token *tempt;
	tempt = (struct token *) malloc (sizeof(struct token)); /*allocate memory */

	tempt->v = fv;
	tempt->type = FLOAT;
	tempt->linenum = linev;

	return tempt;
}

/* register token */
struct token * new_reg_token(int linev, union value regv)
{
	struct token *tempt;
	tempt = (struct token *) malloc (sizeof(struct token)); /*allocate memory */

	tempt->v = regv;
	tempt->type = REGISTER;
	tempt->linenum = linev;

	return tempt;
}

/* opcode token */
struct token * new_op_token(int linev, union value opv)
{
	struct token *tempt;
	tempt = (struct token *) malloc (sizeof(struct token)); /*allocate memory */

	tempt->v = opv;
	tempt->type = OPCODE;
	tempt->linenum = linev;

	return tempt;
}

/* put token on list */
void add_token( struct token *toke, struct tokenlist *tlist)
{
	/* see if this is first token in list */
	if (tlist->head == NULL)
	{
		/* token maintenence */
		toke->prev = NULL;
		toke->next = NULL;
		/* list maintenence */
		tlist->head = toke;
		tlist->tail = toke;
		tlist->current = toke;
	}
	/* just add to existing list */
	else
	{
		/* token maintenence */
		toke->prev = tlist->current;
		toke->next = NULL;
		tlist->current->next = toke;
		/* list maintenence */
		tlist->tail = toke;
		tlist->current = toke;		
	}
	tlist->tokenum++;
}

/* kill token */
void kill_token (struct token *dead)
{
	free(dead);
}


/* clear out a list and free memory */
void clear_list(struct tokenlist *tlist)
{
	/* see if there are any items */
	if (tlist->head != NULL)
	{
		/* set current to head */
		tlist->current = tlist->head;
		
		while (tlist->tokenum != 0)
		{
			/* last token */			
			if(tlist->current->next == NULL)
			{
				kill_token(tlist->current);
				tlist->current = NULL;
				tlist->head = NULL;
				tlist->tail = NULL;
				tlist->tokenum = 0;
			}
			else
			{
				tlist->current = tlist->current->next;
				tlist->head = tlist->current;
				kill_token(tlist->current->prev);
				tlist->current->prev = NULL;
				tlist->tokenum--;
			}
		}
	}
}

/* kill a list */
void kill_list(struct tokenlist *dead)
{
	if(dead->tokenum == 0)
	{	
		free(dead);
	}
	else
	{
		clear_list(dead);
		free(dead);
	}
}







